/**
 * @program: LeetCode
 * @ClassName Num052_getIntersectionNode
 * @description: LeetCode :剑指 Offer 52. 两个链表的第一个公共节点
 * @author: WXY
 * @create: 2022-12-09 20:01
 * @Version 1.0
 **/


public class Num052_getIntersectionNode {
    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    ListNode getIntersectionNode(ListNode head1, ListNode head2) {
        if (head1 == null || head2 == null) {
            return null;
        }
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        int n = 0;
        while (cur1 != null) {
            n++;
            cur1 = cur1.next;
        }
        while (cur2 != null) {
            n--;
            cur2 = cur2.next;
        }
        if (cur1 != cur2) { // cur1 2都来到了最后节点，要是不相交，必然不等
            return null;
        }
        //长的给cur1 ,短的给cur2
        cur1 = n > 0 ? head1 : head2;
        cur2 = cur1 == head1 ? head2: head1;
        n = Math.abs(n);
        while (n != 0) {
            n--;
            cur1 = cur1.next;
        }
        while (cur1 != cur2) {
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return cur1;
    }


}
